// src/utils/useSSE-web.js
import { ref } from 'vue';

export function useSSE() {
  const eventData = ref('');
  const error = ref(null);
  const isConnected = ref(false);
  const eventSource = ref(null);

  // 连接 SSE 服务
  const connect = (url, params, onMessage) => {
    // 关闭已存在的连接
    if (eventSource.value) {
      closeConnection();
    }

    // 构建带参数的URL
    const queryString = new URLSearchParams(params).toString();
    const fullUrl = `${url}?${queryString}`;

    try {
      eventSource.value = new EventSource(fullUrl);
      isConnected.value = true;

      // 监听消息事件
      eventSource.value.onmessage = (event) => {
        const data = event.data;
        eventData.value = data;
        onMessage?.(data);
      };

      // 监听错误事件
      eventSource.value.onerror = (err) => {
        error.value = err;
        isConnected.value = false;
        closeConnection();
      };

      return eventSource.value;
    } catch (err) {
      error.value = err;
      isConnected.value = false;
      return null;
    }
  };

  // 关闭连接
  const closeConnection = () => {
    if (eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
      isConnected.value = false;
    }
  };

  return { 
    eventData, 
    error, 
    isConnected, 
    connect, 
    closeConnection 
  };
}